package indi.qing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import indi.qing.VO.UserLoginVO;
import indi.qing.VO.UserVO;
import indi.qing.common.CodeUtils;
import indi.qing.entity.Device;
import indi.qing.entity.User;
import indi.qing.mapper.DeviceMapper;
import indi.qing.mapper.UserMapper;
import indi.qing.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 熊卿智
 * @since 2021-12-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private DeviceMapper deviceMapper;

    @Override
    public int register(User user) {
        //判断手机号是否存在
        List<User> users = lambdaQuery().eq(User::getPhone, user.getPhone()).list();
        if(!CollectionUtils.isEmpty(users)) {
            throw new RuntimeException("该手机号已被注册");
        }
        String password = user.getPassword();
        //加密
        String encode = CodeUtils.encode(password);
        user.setPassword(encode);
        int insert = userMapper.insert(user);
        return insert;
    }

    @Override
    public UserLoginVO login(String phone, String password, int role) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if(role==1) {
            wrapper.lambda().eq(User::getIsParent,1);
        }
        if(role==2) {
            wrapper.lambda().eq(User::getIsTeacher,1);
        }
        wrapper.eq("phone",phone);
        User one = userMapper.selectOne(wrapper);
        if(one==null) {
            throw new RuntimeException("用户不存在");
        }
        String pwd = CodeUtils.encode(password);
        if(!pwd.equals(one.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        UserLoginVO userLoginVO = new UserLoginVO();
        UserVO userVO = UserToUserVO(one);
        BeanUtils.copyProperties(userVO,userLoginVO);
        if(role==0) {
            userLoginVO.setRole("学生");
        } else if(role==1) {
            userLoginVO.setRole("家长");
        } else if(role==2) {
            userLoginVO.setRole("老师");
        }
        return userLoginVO;
    }

    @Override
    public List<UserVO> findFriend(Long userId, String phone) {
        List<User> users = lambdaQuery().like(User::getPhone, phone).list();
        List<UserVO> res = new ArrayList<>();
        if(CollectionUtils.isEmpty(users)){
            throw new RuntimeException("查无此人");
        }
        users.stream().forEach(user -> {
            if(!Objects.equals(user.getUserId(), userId)){
                UserVO userVO = UserToUserVO(user);
                res.add(userVO);
            }
        });
        return res;
    }

    @Override
    public void bandDevice(Long userId, String deviceSn) {
        QueryWrapper<Device> deviceWrapper = new QueryWrapper<>();
        deviceWrapper.lambda().eq(Device::getDeviceSn,deviceSn);
        Device device = deviceMapper.selectOne(deviceWrapper);
        if(ObjectUtils.isEmpty(device)){
            throw new RuntimeException("序列号不存在");
        }
        if(device.getUserId()!=null){
            throw new RuntimeException("该设备已被绑定");
        }
        device.setUserId(userId);
        UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>();
        deviceUpdateWrapper.lambda()
                .set(Device::getUserId,userId)
                .eq(Device::getDeviceId,device.getDeviceId());
        int update = deviceMapper.update(device, deviceUpdateWrapper);
        if(update==0){
            throw new RuntimeException("绑定失败");
        }
    }

    @Override
    public UserVO findUserById(Long userId) {
        User user = userMapper.selectById(userId);
        if (ObjectUtils.isEmpty(user)){
            throw new RuntimeException("没有此用户");
        }
        return UserToUserVO(user);
    }

    private UserVO UserToUserVO(User user){
        UserVO userVO = new UserVO();
        userVO.setUserId(user.getUserId());
        userVO.setUsername(user.getUsername());
        userVO.setPhone(user.getPhone());
        userVO.setAge(user.getAge());
        if(user.getSex()==null) {
            userVO.setSex("性别未知");
        }
        else if(user.getSex()==0) {
            userVO.setSex("女");
        } else if(user.getSex()==1) {
            userVO.setSex("男");
        }
        return userVO;
    }

}
